#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include "StdTCP.h"
#include <string.h>

#include "StdThread.h"
#include "DLList.h"
#include "ThreadPool.h"
struct Client
{
    char name[20];
    int sock;
};
typedef struct Client ClientLList;
ClientLList *CreateCLList(const char *name, int sock)
{
    ClientLList* c = (ClientLList*)malloc(sizeof(ClientLList));
    if(c == NULL)
    {
        perror("CLL malloc :");
        return NULL;
    }
    strcpy(c->name,name);
    c->sock = sock;
    return c;
}
void FreeCLList(ClientLList* c)
{
    free(c);
    return ;
}

DLList ClientList;



struct message
{
    int flag;
    char fromName[20];
    char toName[20];
    char content[1024];
};
typedef struct message Msg;

 void* thread_handler(void* arg)
 {
    int sock = *((int *)arg);
    while(1)
    {
        
        Msg m ;
        
        TCPServerRecv(sock,&m,sizeof(m));

        switch(m.flag)
        {
            case 1:
                InsertTail(&ClientList,CreateCLList(m.fromName,sock));
                break;
            case 2:
                    struct Node* TravelPoint = ClientList.head;
                    
                    while(TravelPoint != NULL)
                    {
                        ClientLList* c = (ClientLList*)TravelPoint->data;
                        if(strcmp(c->name,m.toName) == 0)
                        {
                            TcpServerSend(c->sock,&m,sizeof(m));
                            break;
                        }
                        TravelPoint = TravelPoint->next;
                    }
                break;
            default:
                break;
        }
    }
 }

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        printf("invaild numbers!\n");
        return -1;
    }
    ThreadP* p = InitThreadPool(100,10,50);
    if(p == NULL)
    {
        printf("ThreadPool is error!\n");
        return -1;
    }
    InitDLList(&ClientList);

    TcpS* s = InitTcpServer( argv[1],atoi(argv[2]));
    int acceptSock ;

    while((acceptSock = TcpServerAccept(s)) > 0)
    {

        ThreadP_AddTask (p,thread_handler,&acceptSock);

       
    }
    //ClearTcpServer(s);
    
    
    return 0;
}



